package com.zzz.common.core.utils;

import com.zzz.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /**
     * 生成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从令牌中获取数据
     *
     * @param token  令牌
     * @param secret 密钥
     * @return Claims： 载荷数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    public static String getUserKey(Claims claims) {
        return toString(claims, JwtConstants.LOGIN_USER_KEY);
    }

    private static String toString(Claims claims, String loginUserKey) {
        Object value = claims.get(loginUserKey);
        if (value == null) {
            return "";
        }
        return value.toString();
    }

    public static String getUserId(Claims claims) {
        return toString(claims, JwtConstants.LOGIN_USER_ID);
    }

    public static void main(String[] args) {
        // 1. 创建载荷数据
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", 12345L);
        claims.put("username", "zhangsan");
        claims.put("role", "admin");

        // 2. 定义密钥
        String secret = "mySecretKey";

        // 3. 生成token
        String token = JwtUtils.createToken(claims, secret);
        System.out.println("生成的JWT Token: " + token);

        // 4. 解析token
        try {
            Claims parsedClaims = JwtUtils.parseToken(token, secret);
            System.out.println("解析出的用户ID: " + parsedClaims.get("userId"));
            System.out.println("解析出的用户名: " + parsedClaims.get("username"));
            System.out.println("解析出的角色: " + parsedClaims.get("role"));
        } catch (Exception e) {
            System.out.println("Token解析失败: " + e.getMessage());
        }
    }
}